package com.ruoyi.car.aspect;

/**
 * ClassName: AutoFillAspect
 * Pacakage: com.ruoyi.car.aspect
 * Description:
 *
 * @Author: 刘松泽
 * @Create 2024/4/25 16:28
 * @Version 1.0
 */

import com.ruoyi.car.annotation.AutoFill;
import com.ruoyi.car.domain.TmdCarList;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.OperationType;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 自定义切面,实现公共字段自动填充
 */

@Aspect
@Component
public class AutoFillListAspect {

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 切入点
     */
    @Pointcut("execution(* com.ruoyi.car.mapper.*.*(..)) && @annotation(com.ruoyi.car.annotation.AutoFill)")
    public void autoFillPointCut() {
    }

    /**
     * 前置通知,在通知中进行公共字段的赋值
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {

        //获得到当前被拦截的方法上的数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();

        //获取当前被拦截的方法的参数--实体对象
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object entity = args[0];
        TmdCarList carList = (TmdCarList) entity;

        //准备赋值的数据
        LocalDateTime now = LocalDateTime.now();
        Long userId = ShiroUtils.getSysUser().getUserId();

        SysUser user = userMapper.getUserByUserId(userId);
        System.out.println(user.getUserName());

        if (operationType == OperationType.INSERT) {
            carList.setCreateTime(new Date());
            carList.setCreatePersonId(user.getUserName());
        }
    }
}
